/**
 * 微信DAT文件解码
 */

const fs = require('fs');
const path = require('path');
const toolsNode = require('../libs/tools-node');
const fileHeaderMarks = {
  'jpg': [0xFF, 0xD8, 0xFF],
  'png': [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A],
  'gif': [0x47, 0x49, 0x46, 0x38, 0x39, 0x61],
  'bmp': [0x42, 0x4D],
  'pcx': [0x0A, 0x05, 0x01, 0x08],
  'webp': [0x52, 0x49, 0x46, 0x46],
  'tif|tiff': [0x49, 0x49, 0x2A, 0x00],
  'TIF|TIFF': [0x4D, 0x4D, 0x00, 0x2A],
  'IFF': [0x46, 0x4F, 0x52, 0x4D],
  'ANI': [0x52, 0x49, 0x46, 0x46],
  'tga|ico|cur': [0x00, 0x00, 0x02, 0x00, 0x00],
  'tga': [0x00, 0x00, 0x02, 0x00, 0x00],
  'ico': [0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x20, 0x20],
  'CUR': [0x00, 0x00, 0x02, 0x00, 0x01, 0x00, 0x20, 0x20],
};
// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];
let _ext = path.extname(from).toLowerCase();
let _name = path.basename(from, '.dat');

if (_ext === '.dat') {
  decodeFile();
}

function decodeFile() {
  let result = {data: null, ext: '', password: ''};
  return new Promise((resolve, reject) => {
    fs.readFile(from, (err, data) => {
      if (err || !data) reject('读取文件错误');
      result.data = data;
      for (let key in fileHeaderMarks) {
        let val = fileHeaderMarks[key] || [];
        let pwd1 = (val[0] || 0) ^ data[0];
        let pwd2 = (val[1] || 0) ^ data[1];
        if (pwd1 === pwd2) {
          result.ext = key;
          result.password = pwd1;
          break;
        }
      }
      if (result.password) {
        result.data = result.data.map(v => (v ^ result.password));
        let decrypted = Buffer.from(result.data);
        let to = path.join(path.dirname(from), `${_name}.${result.ext}`);
        toolsNode.writeFileSync(to, decrypted);
      }
      resolve(result);
    });
  });
};
